package com.letoy.study.service.Impl;

import com.letoy.study.dao.UserDetailsMapper;
import com.letoy.study.entity.UserDetails;
import com.letoy.study.service.UserDetailsService;
import com.letoy.study.utils.ConvertUtils;
import com.letoy.study.vo.UserDetailsVo;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.sql.Timestamp;
import java.util.HashMap;
import java.util.List;

import static com.letoy.study.utils.Constants.FAIL;
import static com.letoy.study.utils.Constants.SUCCESS;

/**
 * @author JiaTianLuo
 * @version 1.0
 * @date 2021/1/26 22:59
 */
@Service
public class UserDetailsServiceImpl implements UserDetailsService {

    @Resource
    private UserDetailsMapper userDetailsMapper;

    @Override
    public HashMap<String, Object> findAll() {
        HashMap<String, Object> hashMap = new HashMap<>();
        List<UserDetails> UserDetailsList = userDetailsMapper.findAll();
        if (UserDetailsList.isEmpty()) {
            hashMap.put("status", "1");
            hashMap.put("msg", "查询失败");
            return hashMap;
        }
        hashMap.put("status", "0");
        hashMap.put("msg", "查询成功");
        hashMap.put("ArticleList", UserDetailsList);
        return hashMap;
    }

    @Override
    public HashMap changeUserDetails(UserDetails userDetails) {
        HashMap<String, Object> hashMap = new HashMap<String, Object>();
        try {
            int result = userDetailsMapper.changeUserDetails(userDetails);
            if (result == 0) {
                hashMap.put("status", "1");
                hashMap.put("msg", "修改失败");
                return hashMap;
            }
        } catch (Exception e) {
            e.printStackTrace();
            hashMap.put("status", "1");
            hashMap.put("msg", "修改失败(error)");
            return hashMap;
        }
        hashMap.put("status", "0");
        hashMap.put("msg", "修改成功");
        return hashMap;
    }

    @Override
    public int initializationUserDetails(UserDetailsVo userDetailsVo) {

        // 使用Spring BeanUtils拷贝Vo到userDetails
        UserDetails userDetails = new UserDetails();
        BeanUtils.copyProperties(userDetailsVo, userDetails);

        // 使用工具类转换时间 将string转换为java.sql.timestamp
        String registerTime = userDetailsVo.getRegisterTime();
        Timestamp timestamp = ConvertUtils.strToSqlDate(registerTime, "yyyy-MM-dd HH:mm:ss");
        userDetails.setRegisterTime(timestamp);

        if (userDetailsMapper.initializationUserDetails(userDetails) >= 1) {
            return SUCCESS;
        } else {
            return FAIL;
        }

    }
}
